import 'package:flutter/material.dart';
import 'package:my_flutter_core/services/navigator_helper.dart';
import 'package:my_flutter_core/utils/color_utils.dart';
import 'package:my_flutter_core/utils/ui_interaction_utils.dart';
import 'package:my_flutter_core/validators/form_text_field_validator.dart';

/// Page provides single text input. It is supposed to be used by detail list.
/// When user clicks on text item for editing.
class SingleInputField extends StatefulWidget {
  const SingleInputField({
    super.key,
    required this.title,
    required this.formTextFieldValidator,
    required this.onConfirmed,
    this.initialValue,
    this.maxLines = 1,
    this.keyboardType = TextInputType.text,
  });

  final String title;
  final FormTextFieldValidator formTextFieldValidator;
  final ValueChanged onConfirmed;
  final int? maxLines;

  final TextInputType? keyboardType;
  final String? initialValue;

  @override
  State<SingleInputField> createState() => _SingleInputFieldState();
}

class _SingleInputFieldState extends State<SingleInputField> {
  final _textEditingController = TextEditingController();
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  @override
  void initState() {
    super.initState();

    _textEditingController.text = widget.initialValue!;
  }

  @override
  void dispose() {
    // Clean up the controller when the widget is disposed.
    _textEditingController.dispose();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: false,
      onPopInvokedWithResult: _onPopInvokedWithResult,
      child: Scaffold(
        appBar: AppBar(
          automaticallyImplyLeading: true,
          title: Text(widget.title),
          actions: <Widget>[
            IconButton(
              padding: const EdgeInsets.only(right: 10.0),
              icon: Text(
                '确认',
                style: TextStyle(
                  color: calculateContrastingColor(
                    Theme.of(context).appBarTheme.backgroundColor!,
                  ),
                ),
              ),
              onPressed: () {
                if (_formKey.currentState!.validate()) {
                  widget.onConfirmed(_textEditingController.text);

                  NavigatorHelper.pop(context);
                }
              },
            ),
          ],
        ),
        body: Form(
          key: _formKey,
          child: Padding(
            padding: const EdgeInsets.symmetric(
              horizontal: 20.0,
              vertical: 10.0,
            ),
            child: TextFormField(
              controller: _textEditingController,
              autofocus: true,
              maxLines: widget.maxLines,
              maxLength: widget.formTextFieldValidator.maxLength,
              keyboardType: widget.keyboardType,
              decoration: InputDecoration(hintText: '请输入${widget.title}'),
              // Validator needs the value which only can get from this view.
              // That's why we create a new [FormTextFieldValidator].
              validator: (value) => FormTextFieldValidator(
                widget.title,
                value,
                isRequired: widget.formTextFieldValidator.isRequired,
                isPositiveNumber:
                    widget.formTextFieldValidator.isPositiveNumber,
                minLength: widget.formTextFieldValidator.minLength,
                maxLength: widget.formTextFieldValidator.maxLength,
                minValue: widget.formTextFieldValidator.minValue,
                maxValue: widget.formTextFieldValidator.maxValue,
                prefix: widget.formTextFieldValidator.prefix,
              ).validate(),
            ),
          ),
        ),
      ),
    );
  }

  /// Checks the data before popping.
  void _onPopInvokedWithResult(bool didPop, dynamic result) {
    if (didPop) {
      return;
    }

    // If the page is popping up while being changed without saving then the confirm dialog will be displayed.
    if (widget.initialValue != _textEditingController.text) {
      showConfirmDialog(
        context,
        '放弃保存？',
        onConfirm: () => NavigatorHelper.pop(context),
      );
    } else {
      // Allows to close current page.
      NavigatorHelper.pop(context);
    }
  }
}
